//
//  RACViewController.m
//  AllDemo
//
//  Created by UgCode on 14-7-5.
//  Copyright (c) 2014年 UgCode. All rights reserved.
//

#import "RACViewController.h"
#import "RACViewControllerModel.h"

#import <ReactiveCocoa.h>

@interface RACViewController ()

@property (weak, nonatomic) IBOutlet UITextField *tflUserName;
@property (weak, nonatomic) IBOutlet UITextField *tflPassword;
@property (weak, nonatomic) IBOutlet UIButton *btnLogIn;
@property (weak, nonatomic) IBOutlet UIButton *btnSignIn;

@property (strong, nonatomic) RACViewControllerModel *model;

@end

@implementation RACViewController

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.model = [[RACViewControllerModel alloc] init];
    
    //把tflUserName的输入内容绑定到model.userName
    RAC(self.model, userName) = self.tflUserName.rac_textSignal;
    //把model.userName改变绑定到tflUserName.text
    RAC(self, tflUserName.text) = [RACObserve(self.model, userName) distinctUntilChanged];
    
    RAC(self.model, password) = self.tflPassword.rac_textSignal;
    RAC(self, tflPassword.text) = [RACObserve(self.model, password) distinctUntilChanged];
    
    RAC(self, btnLogIn.enabled) = [RACObserve(self.model, logInBtnEnabled) distinctUntilChanged];
    //
    RAC(self.model, logInBtnEnabled) = [RACSignal combineLatest:@[[RACObserve(self.model, userName) distinctUntilChanged],
                                                     [RACObserve(self.model, password) distinctUntilChanged]]
                                                         reduce:^id(NSString *userName, NSString *passwold){
                                                             return @(userName.length >= 6 && passwold.length >= 6);
    }];
                           
}

- (IBAction)ShowModelAction:(UIButton *)sender {
    NSLog(@"Model:\n%@", self.model);
}

- (IBAction)addUserName:(UIButton *)sender {
    self.model.userName = [self.model.userName stringByAppendingFormat:@"%@", @"haha!"];
}


- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
